package run.iget.framework.mail.service.impl;

import java.io.File;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import run.iget.framework.common.util.ThreadTaskUtils;
import run.iget.framework.mail.service.MailService;

/**
 * 代码千万行，注释第一行；注释不规范，迭代两行泪
 * ----------------------------------------
 * 邮件发送实现类
 * ----------------------------------------
 * author: 大周
 * date: 2022/2/8 13:03
 **/
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String         from;
    @Value("${spring.mail.nickname:''}")
    private String         nickname;

    @Resource
    private JavaMailSender mailSender;

    /**
     * 对发件人进行编码，支持中文的别名
     *
     * @return urf-8后的发件人
     */
    private String encodedFrom() {
        if (StrUtil.isBlank(nickname)) {
            return from;
        }
        return StrUtil.utf8Str(StrUtil.format("{}<{}>", nickname, from));
    }

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        ThreadTaskUtils.submitTask(() -> {
            SimpleMailMessage message = new SimpleMailMessage();
            //收信人
            message.setTo(to);
            //主题
            message.setSubject(subject);
            //内容
            message.setText(content);
            //发信人
            message.setFrom(encodedFrom());
            mailSender.send(message);
            log.info("发送SimpleMailMessage邮件成功");
        });
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        this.sendHtmlMail(to, subject, content, null, null);
    }

    @Override
    public void sendHtmlMailOfAttachments(String to, String subject, String content,
                                          Map<String, File> attachmentFiles) {
        this.sendHtmlMail(to, subject, content, null, attachmentFiles);
    }

    @Override
    public void sendHtmlMailOfImages(String to, String subject, String content, Map<String, File> imageFiles) {
        this.sendHtmlMail(to, subject, content, imageFiles, null);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content, Map<String, File> imageFiles,
                             Map<String, File> attachmentFiles) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(encodedFrom());
            helper.setTo(to);
            helper.setSubject(subject);
            // true代表支持html
            helper.setText(content, true);
            // 添加图片
            if (CollectionUtil.isNotEmpty(imageFiles)) {
                for (Map.Entry<String, File> imageEntry : imageFiles.entrySet()) {
                    // 重复使用添加多个图片
                    helper.addInline(imageEntry.getKey(), imageEntry.getValue());
                }
            }
            // 添加附件
            if (CollectionUtil.isNotEmpty(attachmentFiles)) {
                for (Map.Entry<String, File> attachmentEntry : attachmentFiles.entrySet()) {
                    // 添加附件，可多次调用该方法添加多个附件
                    helper.addAttachment(attachmentEntry.getKey(), attachmentEntry.getValue());
                }
            }
            // 发送邮件
            ThreadTaskUtils.submitTask(() -> mailSender.send(message));
            log.info("发送HTML邮件成功");
        } catch (MessagingException e) {
            log.error("发送HTML邮件失败：", e);
        }
    }

    @Override
    public void sendInitPasswordEmail(String to, String url) {
        //        Context context = new Context();
        //        context.setVariable("url", url);
        //        String emailContent = templateEngine.process("mail/InitPasswordMail.html", context);
        //        this.sendHtmlMail(to, "重置密码", emailContent);
    }
}
